package com.example.appointment.repository;

import com.example.appointment.entity.Post;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
    Page<Post> findAllByOrderByCreatedAtDesc(Pageable pageable);
    
    Page<Post> findByAuthorIdOrderByCreatedAtDesc(Long authorId, Pageable pageable);
    
    @Query("SELECT p FROM Post p WHERE p.title LIKE %:keyword% OR p.content LIKE %:keyword%")
    Page<Post> searchPosts(String keyword, Pageable pageable);
    
    @Modifying
    @Query("UPDATE Post p SET p.likes = p.likes + 1 WHERE p.id = :id")
    void incrementLikes(Long id);
    
    @Modifying
    @Query("UPDATE Post p SET p.views = p.views + 1 WHERE p.id = :id")
    void incrementViews(Long id);
    
    Page<Post> findAllByOrderByLikesDescCreatedAtDesc(Pageable pageable);
    
    // 获取趋势帖子（一周内点赞最多的帖子）
    @Query("SELECT p FROM Post p WHERE p.createdAt >= :startDate ORDER BY p.likes DESC, p.views DESC, p.createdAt DESC")
    List<Post> findTrendingPosts(@Param("startDate") LocalDateTime startDate, Pageable pageable);
    
    // 统计帖子总数
    @Query("SELECT COUNT(p) FROM Post p")
    Long countTotalPosts();
    
    // 统计今日发布的帖子数
    @Query("SELECT COUNT(p) FROM Post p WHERE p.createdAt >= :today")
    Long countTodayPosts(@Param("today") LocalDateTime today);
    
    // 获取帖子按分类查询
    Page<Post> findByCategoryIdOrderByCreatedAtDesc(Long categoryId, Pageable pageable);

    /**
     * 根据标签查询帖子
     * @param tags 标签（支持模糊匹配）
     * @param pageable 分页参数
     * @return 帖子分页列表
     */
    Page<Post> findByTagsLikeOrderByCreatedAtDesc(String tags, Pageable pageable);

    /**
     * 根据作者ID查询帖子
     * @param authorId 作者ID
     * @param pageable 分页参数
     * @return 帖子分页列表
     */
    Page<Post> findByAuthorId(Long authorId, Pageable pageable);
} 